<template>
  <div class="content-wrapper">
    <div class="content-header">产品项目</div>
    <div class="content-container">
      <el-form ref="listQueryForm" :rules="listQueryRules" :inline="true" :model="listQuery" class="filter-container">
        <el-form-item>
           <el-button
            class="filter-item"
            size="small"
            round
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >
            搜索
          </el-button>
          <el-button class="filter-item" size="small" round icon="el-icon-plus" @click="handleCreate">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table
        v-loading="listLoading"
        :data="list"
        highlight-current-row
      >
        <el-table-column label="产品编码" prop="dictCode" width="200px" />
        <el-table-column label="产品名称" prop="dictValue" min-width="200px" />
        <!-- <el-table-column label="备注" prop="memo" min-width="200px" /> -->
        <el-table-column label="所属大项" min-width="200px">
          <template slot-scope="{row}">
            <span v-if="row.parentDict !== undefined && row.parentDict !== null">{{ row.parentDict.dictValue }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="120px">
          <template slot-scope="{row,$index}">
            <el-dropdown trigger="click" class="filter-item">
              <el-button type="text" class="el-icon-more" />
              <el-dropdown-menu slot="dropdown" class="user-dropdown">
                <el-dropdown-item @click.native="handleUpdate(row)">修改</el-dropdown-item>
                <el-dropdown-item @click.native="handleDelete(row, $index)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" :page-number.sync="listQuery.pageNumber" :page-size.sync="listQuery.pageSize" @pagination="getList" />

      <el-drawer :title="textMap[dialogStatus] + '产品项目'" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="90px">
          <el-form-item v-if="dialogStatus==='create' ? true : false" label="产品编码" prop="dictCode">
            <el-input v-model.trim="temp.dictCode" />
          </el-form-item>
          <el-form-item label="产品名称" prop="dictValue">
            <el-input v-model.trim="temp.dictValue" />
          </el-form-item>
          <!-- <el-form-item label="备注">
            <el-input v-model="temp.memo" />
          </el-form-item> -->
          <el-form-item label="所属大项">
            <el-cascader :key="isParentDictCascaderShow" v-model="selectedParentDictId" :options="parentDictList" :props="{ checkStrictly: true }" filterable clearable @change="handleParentDictIdChange" />
          </el-form-item>
          <el-form-item>
             <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">提交</el-button>
          </el-form-item>
        </el-form>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { listDict, saveDict, updateDict, deleteDict, listDictTreeItemForManage } from '@/api/base/dict'
import Pagination from '@/components/Pagination'
import waves from '@/directive/waves'
import { findAndAccept3 } from '@/utils/tree'

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      list: [],
      total: 0,
      listLoading: false,
      listQuery: {
        pageNumber: 1,
        pageIndex: 0,
        pageSize: 20,
        dictGroupCode: 'product',
        dictCode: null,
        withParent: true
      },
      temp: {
        dictId: null,
        dictGroupCode: 'product',
        dictCode: null,
        dictValue: null,
        memo: null,
        sequence: 1,
        parentDictId: null,
      },
      parentDictList: [],
      selectedParentDictId: [],
      isParentDictCascaderShow: '0',
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      listQueryRules: {
        dictGroupCode: [{ required: true, message: '类组不能为空', trigger: 'change' }],
      },
      rules: {
        dictCode: [
          { required: true, message: '代码不能为空', trigger: 'change' },
          { pattern: /^[a-zA-Z0-9_-]+$/, message: '代码由a-zA-Z0-9_-等字母组成', trigger: 'change' }
        ],
        dictValue: [{ required: true, message: '文本不能为空', trigger: 'change' }],
        sequence: [{ required: true, message: '排序不能为空', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    handleDictGroupCodeChange(value) {
      this.showParentDictList()
      this.handleFilter()
    },
    getList() {
      this.listQuery.pageIndex = this.listQuery.pageNumber - 1
      this.listLoading = true
      listDict(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.$refs['listQueryForm'].validate((valid) => {
        if (valid) {
          this.listQuery.pageNumber = 1
          this.getList()
        }
      })
    },
    showParentDictList() {
      if (this.listQuery.dictGroupCode) {
        listDictTreeItemForManage({
          dictGroupCode: this.listQuery.dictGroupCode
        }).then(response => {
          this.parentDictList = response.data
        })
      }
    },
    handleParentDictIdChange(value) {
      if (value) {
        this.temp.parentDictId = value[value.length - 1]
      }
    },
    resetTemp() {
      this.temp = {
        dictId: null,
        dictGroupCode: this.listQuery.dictGroupCode,
        dictCode: null,
        dictValue: null,
        memo: null,
        sequence: 1,
        parentDictId: null
      }
    },
    clearParentDictCascader() {
      this.selectedParentDictId.length = 0
      ++this.isParentDictCascaderShow
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.clearParentDictCascader()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          saveDict(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.handleFilter()
            this.showParentDictList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
      const parentStack = findAndAccept3(this.parentDictList,
        e => this.temp.parentDictId === e.value,
        e => { this.temp.parentDictName = e.label })
      this.clearParentDictCascader()
      parentStack.forEach(e => {
        this.selectedParentDictId.push(e.value)
      })
      this.$forceUpdate()
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateDict(tempData).then(() => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.handleFilter()
            this.showParentDictList()
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作将删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDict({
          dictId: row.dictId
        }).then(response => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getList()
        })
      })
    }

  }
}
</script>

<style scoped>
  
</style>
